<?php

namespace app\common\model;

use think\Db;
use think\Model;

class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'addtime';
    protected $updateTime = 'edittime';
    // 追加属性
    protected $append = ['image'];

    /**
     * 获取用户信息
     * @param int $user_id 用户id
     */
    public static function user_info(int $user_id)
    {
        $where = "id = {$user_id}";
        $info = self::where($where)->field("*")->find()->toArray();
        $cleaned_data = array_map(function ($value) {
            return ($value === null) ? "" : $value;
        }, $info);
        return $cleaned_data;
    }

    /**
     * 登录方法
     * @param string $union_id
     * @param string $openid
     * @param string $head_img
     * @param string $nickname
     */
    public static function login($openid,$pid)
    {
        $where = "open_id = '{$openid}'";
        $info = self::where($where)->order("id","desc")->find();
        $isStore = strpos($pid, 'store_');
        if (empty($info)){
            $time = time();
            $insert = [
                'username'=>randomNumber(),
                'tel'=>'',
                'is_jin'=>0,
                'image'=>'/avatar.png',
                'open_id'=>$openid,
                'addtime'=>$time,
                'edittime'=>$time,
            ];

            if ($isStore !== false) {
                //空间分享
                $storeArr = explode('store_',$pid);
                $storeId = $storeArr[1];
                $insert['pid'] = 0;
                $insert['two_pid'] = 0;
                $insert['store_id'] = $storeId;
            } else {
                //用户分享

                //上下级绑定
                if (!empty($pid)) {
                    $pUser = db('user')->where('id',$pid)->find();
                    if (!empty($pUser)) {
                        if (!empty($pUser['store_id'])) {
                            $insert['pid'] = $pid;
                            $insert['store_id'] = $pUser['store_id'];
                            if (!empty($pUser['pid'])) {
                                $insert['two_pid'] = $pUser['pid'];
                            }
                        }
                    }
                }
            }


            
            //var_dump($insert);die;
            return self::create($insert);
        }else{

            if ($isStore !== false) {
                //空间分享
                if (empty($info['store_id'])) {
                    $storeArr = explode('store_',$pid);
                    $storeId = $storeArr[1];

                    db('user')->where('id',$info['id'])->update([
                        'store_id'=>$storeId,
                        'pid'=>0,
                        'two_pid'=>0
                    ]);

                }
            } else {
                //用户分享

                //上下级绑定
                if (!empty($pid)) {
                    $updateArr = [];
                    $pUser = db('user')->where('id',$pid)->find();
                    if (!empty($pUser)) {
                        if (!empty($pUser['store_id'])) {
                            if (empty($info['store_id'])) {
                                $updateArr['store_id'] = $pUser['store_id'];
                                $updateArr['pid'] = $pid;
                                if (!empty($pUser['pid'])) {
                                    $updateArr['two_pid'] = $pUser['pid'];
                                }
                            }
                            if (!empty($updateArr)) {
                                db('user')->where('id',$info['id'])->update($updateArr);
                            }   
                        } 
                    }
                }
            }

            $info = self::where($where)->order("id","desc")->find();
            return $info;
        }
    }

    /**
     * 获取个人头像
     */
    public function getImageAttr($value)
    {
        if($value){
            return splicing_domain($value);
        }else{
            return "";
        }
    }


    public function getIdCard1ImageAttr($value)
    {
        if($value){
            return splicing_domain($value);
        }else{
            return "";
        }
    }

    public function getIdCard2ImageAttr($value)
    {
        if($value){
            return splicing_domain($value);
        }else{
            return "";
        }
    }

    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        //return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                UserCircle::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                Report::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

}
